package com.ssm.controller.system;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import com.ssm.common.Message;
import com.ssm.entity.system.Operator;
import com.ssm.entity.system.Role;
import com.ssm.service.system.OperatorService;
import com.ssm.service.system.RoleService;
import com.ssm.util.ExcelUtil;
import com.ssm.web.Page;

@Controller
@RequestMapping("system/operator")
public class OperatorController {
	
	@Autowired
	private OperatorService operatorService;
	
	@Autowired
	private RoleService roleService;
	
	@RequestMapping("list")
	public ModelAndView list(ModelAndView mav, HttpServletResponse response, Operator operator, Integer isExport) {
		Page<Operator> page = operatorService.queryList(operator);
		if (isExport != null && isExport == 1) {
			ExcelUtil<Operator> excelUtil = new ExcelUtil<Operator>();
	        String[] columnNames = new String[] {"用户名", "姓名", "性别", "出生年", "出生月", "出生日", "状态", "住址", "手机", "电话", "创建人", "创建时间"};
			String[] columnMethods = new String[] {"id", "name", "sex", "year", "month", "day", "state", "address", "mobile", "phone", "creater", "createTime"};
			try {
				String codedFileName = URLEncoder.encode("导出", "UTF-8");
				excelUtil.getWorkbook(columnNames, columnMethods, page.getRecord(), response.getOutputStream(), "yyyy-MM-dd HH:mm:ss");
				response.setHeader("Content-disposition", "attachment; filename=" + codedFileName + ".xls");
				response.setContentType("application/msexcel");
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
		mav.addObject(page);
		mav.setViewName("system/operator/list");
		return mav;
	}
	
	@RequestMapping("getDetail")
	public ModelAndView getDetail(ModelAndView mav, String operatorId) {
		Operator operator = operatorService.getDetail(operatorId);
		mav.addObject(operator);
		mav.setViewName("system/operator/detail");
		return mav;
	}
	
	@RequestMapping("toAdd")
	public ModelAndView toAdd() {
		Role role = new Role();
		Page<Role> page = roleService.queryList(role);
		ModelAndView mav = new ModelAndView("system/operator/add");
		mav.addObject("roleList", page.getRecord());
		return mav;
	}
	
	@RequestMapping("add")
	@ResponseBody
	public Object add(ModelAndView mav, Operator operator) {
		return operatorService.save(operator);
	}
	
	@RequestMapping("delete")
	@ResponseBody
	public Object delete(@RequestParam("ids[]") String[] ids) {
		return operatorService.delete(ids);
	}
	
	@RequestMapping("toUpdate")
	public ModelAndView toUpdate(ModelAndView mav, String operatorId) {
		Operator operator = operatorService.getDetail(operatorId);
		Role role = new Role();
		List<Role> roleList = roleService.queryList(role).getRecord();
		mav.addObject(operator);
		mav.addObject(roleList);
		mav.setViewName("system/operator/update");
		return mav;
	}
	
	@RequestMapping("update")
	@ResponseBody
	public Object update(Operator operator) {
		return operatorService.update(operator);
	}
	
	@RequestMapping("toUpload")
	public String toUpload() {
		return "system/operator/upload";
	}
	
	@RequestMapping("upload")
	@ResponseBody
	public Object upload(HttpServletRequest request) {
		long startTime = System.currentTimeMillis();
		//将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		//request
		//检查form中是否有enctype="multipart/form-data"
		if(multipartResolver.isMultipart(request)) {
			//将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			//获取multiRequest 中所有的文件名
			Iterator<String> iter = multiRequest.getFileNames();
			while(iter.hasNext()) {
				//一次遍历所有文件
				MultipartFile file=multiRequest.getFile(iter.next().toString());
				if (file.getSize() == 0) {
					return "error";
				}
				try {
					FileUtils.copyInputStreamToFile(
							file.getInputStream(),
							new File(System.getProperty("springmvcsm_eui.root")+"../upload/" +file.getOriginalFilename()));
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		long endTime=System.currentTimeMillis();
		System.out.println("方法三的运行时间："+String.valueOf(endTime-startTime)+"ms");
		return "success";
	}
	
	@RequestMapping("toImport")
	public String toImport() {
		return "system/operator/import";
	}
	
	@RequestMapping("imports")
	public String imports(HttpServletRequest request) throws IOException {
		MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = mulRequest.getFile("uploadFile");
        String filename = file.getOriginalFilename();
        if (filename == null || "".equals(filename)) {
            return null;
        }
		Message message = operatorService.imports(file.getInputStream());
		if (message.isSuccess()) {
			return "success";
		}
		return "error";
	}
	
	@RequestMapping("loadName")
	@ResponseBody
	public Object loadName(String keyword) {
		Operator operator = new Operator();
		operator.setName(keyword);
		Page<Operator> page = operatorService.queryList(operator);
		List<String> list = new ArrayList<>();
		for (Operator o : page.getRecord()) {
			list.add(o.getName());
		}
		return list;
	}
}
